#!/bin/bash
# FastLED JavaScript/TypeScript Linting Script (Node.js + ESLint + JSDoc Type Checking - FAST!)

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Store project root directory for cache operations
PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"

# Set up trap to invalidate cache on failure
trap 'if [ $? -ne 0 ]; then cd "$PROJECT_ROOT" && uv run python ci/js_lint_cache.py failure; fi' EXIT

echo -e "${BLUE}FAST FastLED JavaScript/TypeScript Linting (Node.js + ESLint + JSDoc Type Checking - FAST!)${NC}"

# Check if ESLint is installed
if [ ! -f ".cache/js-tools/node_modules/.bin/eslint.cmd" ]; then
    echo -e "${RED}ERROR: ESLint not found. Run: uv run ci/setup-js-linting-fast.py${NC}"
    exit 1
fi

# Check if JS files need linting using fingerprint cache (from project root)
# Skip cache check if FASTLED_NO_FINGERPRINT is set
if [ "${FASTLED_NO_FINGERPRINT:-0}" = "1" ]; then
    echo -e "${BLUE}📋 Skipping cache check (--no-fingerprint flag set)${NC}"
else
    echo -e "${BLUE}🔍 Checking if JavaScript files need linting...${NC}"
    cd "$PROJECT_ROOT"
    if uv run python ci/js_lint_cache.py check; then
        echo -e "${BLUE}📋 JavaScript files changed - proceeding with linting${NC}"
    else
        echo -e "${GREEN}⚡ No changes detected - skipping JavaScript linting${NC}"
        exit 0
    fi
fi

# Find JavaScript and TypeScript files (exclude node_modules and vendor)
JS_FILES=$(find src/platforms/wasm -name "*.js" -type f -not -path "*/node_modules/*" -not -path "*/vendor/*" 2>/dev/null)
TS_FILES=$(find ci/docker/avr8js -name "*.ts" -type f -not -path "*/node_modules/*" 2>/dev/null)

if [ -z "$JS_FILES" ] && [ -z "$TS_FILES" ]; then
    echo -e "${YELLOW}WARNING: No JavaScript or TypeScript files found${NC}"
    exit 0
fi

if [ -n "$JS_FILES" ]; then
    echo -e "${BLUE}Found JavaScript files:${NC}"
    echo "$JS_FILES" | sed 's/^/  /'
fi

if [ -n "$TS_FILES" ]; then
    echo -e "${BLUE}Found TypeScript files:${NC}"
    echo "$TS_FILES" | sed 's/^/  /'
fi

# Run ESLint using config from ci/ directory
echo -e "${BLUE}Running ESLint...${NC}"
cd .cache/js-tools

# Build the list of files/patterns to lint
LINT_TARGETS=()

# Add JavaScript files if they exist
if [ -n "$JS_FILES" ]; then
    LINT_TARGETS+=("../../src/platforms/wasm/compiler/*.js")
    LINT_TARGETS+=("../../src/platforms/wasm/compiler/modules/**/*.js")
fi

# Add TypeScript files if they exist
if [ -n "$TS_FILES" ]; then
    LINT_TARGETS+=("../../ci/docker/avr8js/*.ts")
fi

if "./node_modules/.bin/eslint.cmd" --no-eslintrc --no-inline-config -c .eslintrc.js "${LINT_TARGETS[@]}"; then
    echo -e "${GREEN}✅ ESLint completed successfully${NC}"
else
    echo -e "${RED}ERROR: ESLint failed${NC}"
    cd "$PROJECT_ROOT" && uv run python ci/js_lint_cache.py failure
    exit 1
fi

# Run JSDoc Type Checking using TypeScript
echo -e "${BLUE}Running JSDoc Type Checking...${NC}"
cd ../../src/platforms/wasm/compiler

# Check if TypeScript is available (local installation first, then global)
if [ -f "../../../../.cache/js-tools/node_modules/.bin/tsc.cmd" ]; then
    echo -e "${BLUE}Using local TypeScript for JSDoc type checking...${NC}"
    # Run TypeScript and filter out Node.js events library errors and vendor files
    TSC_OUTPUT=$(../../../../.cache/js-tools/node_modules/.bin/tsc.cmd --noEmit --project jsconfig.json 2>&1)
    TSC_EXIT_CODE=$?
    # Filter out Node.js events error and vendor directory errors (third-party code)
    # This awk script filters out vendor errors and their continuation lines (which start with spaces)
    FILTERED_OUTPUT=$(echo "$TSC_OUTPUT" | awk '/^vendor\// {skip=1; next} /^[^ ]/ {skip=0} !skip {print}' | grep -v "node_modules/events/events.js.*Property 'context' does not exist on type 'Error'" || true)

    if [ -n "$FILTERED_OUTPUT" ]; then
        echo "$FILTERED_OUTPUT"
        if [ $TSC_EXIT_CODE -ne 0 ]; then
            echo -e "${RED}❌ JSDoc type checking failed with errors${NC}"
            cd "$PROJECT_ROOT" && uv run python ci/js_lint_cache.py failure
            exit 1
        fi
    fi
    echo -e "${GREEN}✅ JSDoc type checking completed successfully${NC}"
elif [ -f "../../../../.cache/js-tools/node_modules/.bin/tsc" ]; then
    echo -e "${BLUE}Using local TypeScript for JSDoc type checking...${NC}"
    # Run TypeScript and filter out Node.js events library errors and vendor files
    TSC_OUTPUT=$(../../../../.cache/js-tools/node_modules/.bin/tsc --noEmit --project jsconfig.json 2>&1)
    TSC_EXIT_CODE=$?
    # Filter out Node.js events error and vendor directory errors (third-party code)
    # This awk script filters out vendor errors and their continuation lines (which start with spaces)
    FILTERED_OUTPUT=$(echo "$TSC_OUTPUT" | awk '/^vendor\// {skip=1; next} /^[^ ]/ {skip=0} !skip {print}' | grep -v "node_modules/events/events.js.*Property 'context' does not exist on type 'Error'" || true)

    if [ -n "$FILTERED_OUTPUT" ]; then
        echo "$FILTERED_OUTPUT"
        if [ $TSC_EXIT_CODE -ne 0 ]; then
            echo -e "${RED}❌ JSDoc type checking failed with errors${NC}"
            cd "$PROJECT_ROOT" && uv run python ci/js_lint_cache.py failure
            exit 1
        fi
    fi
    echo -e "${GREEN}✅ JSDoc type checking completed successfully${NC}"
elif command -v npx >/dev/null 2>&1 && npx tsc --version >/dev/null 2>&1; then
    echo -e "${BLUE}Using global TypeScript for JSDoc type checking...${NC}"
    # Run TypeScript and filter out Node.js events library errors
    TSC_OUTPUT=$(npx tsc --noEmit --project jsconfig.json 2>&1)
    TSC_EXIT_CODE=$?
    # Filter out the specific Node.js events error
    FILTERED_OUTPUT=$(echo "$TSC_OUTPUT" | grep -v "node_modules/events/events.js.*Property 'context' does not exist on type 'Error'" || true)

    if [ -n "$FILTERED_OUTPUT" ]; then
        echo "$FILTERED_OUTPUT"
        if [ $TSC_EXIT_CODE -ne 0 ]; then
            echo -e "${RED}❌ JSDoc type checking failed with errors${NC}"
            cd "$PROJECT_ROOT" && uv run python ci/js_lint_cache.py failure
            exit 1
        fi
    fi
    echo -e "${GREEN}✅ JSDoc type checking completed successfully${NC}"
else
    echo -e "${YELLOW}⚠️  TypeScript not found, skipping JSDoc type checking${NC}"
    echo -e "${BLUE}💡 To enable JSDoc checking: Run the ./install script or npm install -g typescript${NC}"
fi

echo -e "${GREEN}SUCCESS: JavaScript/TypeScript linting and type checking completed successfully${NC}"

# Mark linting as successful in cache (from project root)
# Skip if FASTLED_NO_FINGERPRINT is set (no cache check was performed)
if [ "${FASTLED_NO_FINGERPRINT:-0}" != "1" ]; then
    cd "$PROJECT_ROOT"
    uv run python ci/js_lint_cache.py success
fi